const player = document.getElementById('player');
let loopMode = false;
let randomMode = false;
let currentPlayingButton = null;

// 播放统计数据
let playStats = JSON.parse(localStorage.getItem('playStats')) || {
  totalPlays: 0,
  audioStats: {},
  mostPopular: null
};

// 所有音频按钮的数组
let allAudioButtons = [];

// 页面加载动画和初始化
document.addEventListener('DOMContentLoaded', () => {
  const sections = document.querySelectorAll('.section');
  sections.forEach((section, index) => {
    section.style.opacity = '0';
    section.style.transform = 'translateY(30px)';

    setTimeout(() => {
      section.style.transition = 'all 0.6s ease-out';
      section.style.opacity = '1';
      section.style.transform = 'translateY(0)';
    }, index * 200);
  });

  // 初始化功能
  initializeAudioButtons();
  initializeVolumeControl();
  updateStatsDisplay();
});

// 初始化音频按钮数组
function initializeAudioButtons() {
  allAudioButtons = Array.from(document.querySelectorAll('button[data-audio]'));
}

// 音频按钮点击事件
document.querySelectorAll('button[data-audio]').forEach(button => {
  button.addEventListener('click', () => {
    playAudio(button);
  });
});

// 播放音频函数
function playAudio(button) {
  const audioSrc = button.getAttribute('data-audio');
  const audioName = button.textContent.trim();

  // 重置之前播放的按钮状态
  if (currentPlayingButton && currentPlayingButton !== button) {
    currentPlayingButton.classList.remove('playing');
  }

  // 设置当前播放按钮
  currentPlayingButton = button;
  button.classList.add('playing');

  // 播放音频
  player.src = audioSrc;
  player.loop = loopMode;
  player.play().catch(error => {
    console.log('播放失败:', error);
    button.classList.remove('playing');
    return;
  });

  // 更新播放统计
  updatePlayStats(audioSrc, audioName);

  // 添加点击动画效果
  button.style.transform = 'scale(0.95)';
  setTimeout(() => {
    button.style.transform = '';
  }, 150);
}

// 循环模式切换
const loopButton = document.getElementById('loop');
loopButton.addEventListener('click', () => {
  loopMode = !loopMode;

  if (loopMode) {
    loopButton.classList.add('active');
    loopButton.innerHTML = '<i class="ri-loop-left-line"></i> 循环开启';
    // 关闭随机模式
    if (randomMode) {
      toggleRandomMode();
    }
  } else {
    loopButton.classList.remove('active');
    loopButton.innerHTML = '<i class="ri-loop-left-line"></i> 单曲循环';
  }

  // 如果当前有音频在播放，更新循环状态
  if (player.src) {
    player.loop = loopMode;
  }

  // 显示状态提示
  showToast(`单曲循环：${loopMode ? '已开启' : '已关闭'}`);
});

// 随机播放模式切换
const randomButton = document.getElementById('random');
randomButton.addEventListener('click', () => {
  toggleRandomMode();
});

function toggleRandomMode() {
  randomMode = !randomMode;

  if (randomMode) {
    randomButton.classList.add('active');
    randomButton.innerHTML = '<i class="ri-shuffle-line"></i> 随机开启';
    // 关闭循环模式
    if (loopMode) {
      loopMode = false;
      loopButton.classList.remove('active');
      loopButton.innerHTML = '<i class="ri-loop-left-line"></i> 单曲循环';
      player.loop = false;
    }
  } else {
    randomButton.classList.remove('active');
    randomButton.innerHTML = '<i class="ri-shuffle-line"></i> 随机播放';
  }

  showToast(`随机播放：${randomMode ? '已开启' : '已关闭'}`);
}

// 随机播放下一首
function playRandomAudio() {
  if (allAudioButtons.length === 0) return;

  let randomButton;
  do {
    const randomIndex = Math.floor(Math.random() * allAudioButtons.length);
    randomButton = allAudioButtons[randomIndex];
  } while (randomButton === currentPlayingButton && allAudioButtons.length > 1);

  playAudio(randomButton);
}

// 停止播放
document.getElementById('stop').addEventListener('click', () => {
  player.pause();
  player.currentTime = 0;

  // 重置所有按钮状态
  if (currentPlayingButton) {
    currentPlayingButton.classList.remove('playing');
    currentPlayingButton = null;
  }

  showToast('播放已停止');
});

// 音频播放结束事件
player.addEventListener('ended', () => {
  if (currentPlayingButton) {
    currentPlayingButton.classList.remove('playing');

    if (randomMode) {
      // 随机播放下一首
      playRandomAudio();
    } else if (!loopMode) {
      // 非循环模式下停止播放
      currentPlayingButton = null;
      updateCurrentPlayingDisplay('无');
    }
  }
});

// 音频播放错误事件
player.addEventListener('error', () => {
  if (currentPlayingButton) {
    currentPlayingButton.classList.remove('playing');
    currentPlayingButton = null;
  }
  updateCurrentPlayingDisplay('无');
  showToast('音频加载失败，请检查文件路径');
});

// 音量控制初始化
function initializeVolumeControl() {
  const volumeSlider = document.getElementById('volume-slider');
  const volumeValue = document.getElementById('volume-value');

  // 从本地存储读取音量设置
  const savedVolume = localStorage.getItem('audioVolume') || 50;
  volumeSlider.value = savedVolume;
  volumeValue.textContent = savedVolume + '%';
  player.volume = savedVolume / 100;

  // 音量滑块事件
  volumeSlider.addEventListener('input', (e) => {
    const volume = e.target.value;
    volumeValue.textContent = volume + '%';
    player.volume = volume / 100;

    // 保存到本地存储
    localStorage.setItem('audioVolume', volume);

    // 更新音量图标
    updateVolumeIcon(volume);
  });

  // 初始化音量图标
  updateVolumeIcon(savedVolume);
}

// 更新音量图标
function updateVolumeIcon(volume) {
  const volumeLabel = document.querySelector('.volume-control label i');
  if (volume == 0) {
    volumeLabel.className = 'ri-volume-mute-line';
  } else if (volume < 30) {
    volumeLabel.className = 'ri-volume-down-line';
  } else {
    volumeLabel.className = 'ri-volume-up-line';
  }
}

// 播放统计功能
function updatePlayStats(audioSrc, audioName) {
  // 更新总播放次数
  playStats.totalPlays++;

  // 更新单个音频统计
  if (!playStats.audioStats[audioSrc]) {
    playStats.audioStats[audioSrc] = {
      name: audioName,
      count: 0
    };
  }
  playStats.audioStats[audioSrc].count++;

  // 更新最受欢迎的音频
  let maxCount = 0;
  let mostPopular = null;
  for (const [src, stats] of Object.entries(playStats.audioStats)) {
    if (stats.count > maxCount) {
      maxCount = stats.count;
      mostPopular = stats.name;
    }
  }
  playStats.mostPopular = mostPopular;

  // 保存到本地存储
  localStorage.setItem('playStats', JSON.stringify(playStats));

  // 更新显示
  updateStatsDisplay();
  updateCurrentPlayingDisplay(audioName);
}

// 更新统计显示
function updateStatsDisplay() {
  document.getElementById('total-plays').textContent = playStats.totalPlays;
  document.getElementById('most-popular').textContent = playStats.mostPopular || '暂无数据';
}

// 更新当前播放显示
function updateCurrentPlayingDisplay(audioName) {
  document.getElementById('current-playing').textContent = audioName;
}

// 重置统计数据
document.getElementById('reset-stats').addEventListener('click', () => {
  if (confirm('确定要重置所有播放统计数据吗？')) {
    playStats = {
      totalPlays: 0,
      audioStats: {},
      mostPopular: null
    };
    localStorage.setItem('playStats', JSON.stringify(playStats));
    updateStatsDisplay();
    updateCurrentPlayingDisplay('无');
    showToast('统计数据已重置');
  }
});

// 提示消息函数
function showToast(message) {
  // 移除已存在的提示
  const existingToast = document.querySelector('.toast');
  if (existingToast) {
    existingToast.remove();
  }

  // 创建新提示
  const toast = document.createElement('div');
  toast.className = 'toast';
  toast.textContent = message;
  toast.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    background: rgba(0,0,0,0.8);
    color: white;
    padding: 12px 20px;
    border-radius: 25px;
    font-size: 14px;
    z-index: 1000;
    animation: slideInRight 0.3s ease-out;
    backdrop-filter: blur(10px);
  `;

  document.body.appendChild(toast);

  // 3秒后自动移除
  setTimeout(() => {
    toast.style.animation = 'slideOutRight 0.3s ease-in';
    setTimeout(() => {
      if (toast.parentNode) {
        toast.remove();
      }
    }, 300);
  }, 3000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
  @keyframes slideInRight {
    from {
      transform: translateX(100%);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }

  @keyframes slideOutRight {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(100%);
      opacity: 0;
    }
  }

  .playing {
    animation: playingPulse 1.5s ease-in-out infinite !important;
    box-shadow: 0 0 20px rgba(255,255,255,0.5) !important;
  }

  @keyframes playingPulse {
    0%, 100% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.05);
    }
  }
`;
document.head.appendChild(style);
